<template>
    <div>
        <el-row :gutter="6">
            <el-col :span="4">
                <div class="lable-wrap category">
                    <label for="">分类:</label>
                    <div class="wrap-content">
                        <el-select v-model="category_value" placeholder="请选择" style="width:100%;">
                        <el-option
                            v-for="item in options.category"
                            :key="item.id"
                            :label="item.category_name"
                            :value="item.id">
                        </el-option>
                        </el-select>
                    </div>
                </div>
            </el-col>
            <el-col :span="8">
                <div class="lable-wrap date">
                    <label for="">日期:</label>
                    <div class="wrap-content" >
                    <el-date-picker
                        style="width: 100%;"
                        v-model="date_value"
                        type="datetimerange"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        align="right"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :default-time="['12:00:00', '08:00:00']">
                    </el-date-picker>
                    </div>
                </div>               
            </el-col>
            <el-col :span="4">
                <div class="lable-wrap key-work">
                    <label for="">关键字:</label>
                    <div class="wrap-content">
                    <seleteKey :config="options.configOption"></seleteKey>    
                    <!-- <el-select v-model="search_key" style="width:100%;">
                        <el-option
                            v-for="item in search_option" 
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select> -->
                    </div>
                </div>
            </el-col>
            <el-col :span="4">
                <el-input v-model="search_keyWork" placeholder="请输入内容"></el-input>
            </el-col>
            <el-col :span="2">
                <el-button type="danger" @click="table_search">搜索</el-button>
            </el-col>
            <el-col :span="2">
                <el-button class="pull-right" type="danger" @click="dialog_info = true">新增</el-button>
            </el-col>
        </el-row>
        <div class="black-space-30"></div>
        <el-table :data="table_data.table_dataItem" v-loading="loading_table_data" @selection-change="handleSelectionChange" border style="width: 100%">
            <el-table-column type="selection" width="39"></el-table-column>
            <el-table-column prop="title" label="标题" width="360" fixed="left"></el-table-column>
            <el-table-column prop="categoryId" label="类型" width="100" :formatter="table_categoryId"></el-table-column>
            <el-table-column prop="createDate" label="日期" width="180" :formatter="table_time"></el-table-column>
            <el-table-column prop="user" label="管理员" width="130"></el-table-column>
            <el-table-column label="操作" width="240" fixed="right">
                <template slot-scope="scope" >
                <div class="text-center">
                    <el-button size="mini" type="success" @click="dialogEdit(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
                    <!-- 简化代码 编程式路由通过JS来控制路由的跳转-->
                    <el-button size="mini" type="danger" @click="detail(scope.row)">查看</el-button>
                    <!-- 五组件会被渲染到<router-view>种传参方式 query:{id: scoped.row.id}}" <--明文传参方式 密文传参方式--》params:{"id: scoped.row.id"} -->
                    <!-- 在App.vue中所加载的</router-view>容器中 -->
                    <!-- <router-link :to="{name: 'InfoDetail', query:{id: scope.row.id, title:scope.row.title}}" class="margin-left-10">
                        <el-button size="mini" type="danger">查看</el-button>
                    </router-link> -->
                </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="black-space-30"></div>
        <el-row>
            <el-col :span="12">
                <el-button size="medium" @click="deleteAll">批量删除</el-button>
            </el-col>
            <el-col :span="12">
                <el-pagination
                    class="pull-right"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </el-col>
        </el-row>
        <!-- 调用弹窗  .sync修饰器，简约代码  回调方法this.$emit()回调需要做逻辑处理时不能用修饰器 @close="closeDialog"可不要 :categoryt通过传参的方式-->
        <!--新增弹窗 -->
        <dialogInfo :flag.sync="dialog_info" :category="options.category"></dialogInfo>
        <!-- 编辑弹窗 -->
        <dialogEdit :flag.sync="dialog_edit" :id="editId" :category="options.category"></dialogEdit>
    </div>
</template>

<script>
import { GetCategory, GetList, DeleteInfo } from "../../api/news";
import dialogInfo from "./dialog/info";
import dialogEdit from "../Info/dialog/edit";
import seleteKey from "../../components/Selete/selete";
import { global } from "../../utils/global_3.0";
import { common } from "../../api/common";
import {timestampToTime }  from "../../utils/common";
import { reactive ,ref ,onMounted, watch } from '@vue/composition-api';
export default {
    name: "InfoIndex",
    components :{ dialogInfo, dialogEdit, seleteKey},
    setup(props,{root}){
        const { categoryItem } = common();
        const { str, confirm } = global();  
        const dialog_info = ref(false);   //触发true、false的切换
        const dialog_edit = ref(false);   //触发true、false的切换
        const search_key = ref('id');
        const category_value = ref('');
        const date_value = ref('');
        const search_keyWork = ref('');
        const total = ref(0);
        //调用 Loading 的方法v-loading，绑定Boolean
        const loading_table_data = ref(false);
        const deleteInfoId = ref('');
        const editId = ref("");

        const options = reactive({
            configOption: ["id","title"],
            category:[]
            // {
            // value: 1,
            // label: '黄金糕'
            // }, {
            // value: 2,
            // label: '双皮奶'
            // }, {
            // value: 3,
            // label: '蚵仔煎'
            // }
        });
        const table_search = (()=>{
            // console.log(category_value.value);
            // console.log(search_key.value)
            // console.log(date_value.value)
            // console.log(search_keyWork.value)
            getList();

        })
        //按条件搜索
        const formatData = () => {
            let requestData = {
                pageNumber: page.pageNumber,
                pageSize: page.pageSize
            };
            // 分类ID
            if(category_value.value) { requestData.categoryId = category_value.value }
            // 日期
            if(date_value.value.length > 0) {
                requestData.startTiem = date_value.value[0]
                requestData.endTime = date_value.value[1]
            }
            // 关键字
            if(search_keyWork.value) { requestData[search_key.value] = search_keyWork.value; }
            return requestData;
        }
        const table_data = reactive({
            table_dataItem:[]
        })
        //用来格式化内容Function(row, column, cellValue, index)
        const table_time = ((row, column, cellValue, index)=>{
            // console.log(row,'row')
            return timestampToTime(row.createDate)
        })
        const table_categoryId = ((row)=>{
            // console.log(row,'row')
            // 调用一个函数，返回一个新的值，替换原始值,请求接口获取的Id
            let categoryId = row.categoryId;
            let table_categoryData = options.category.filter(item => item.id == categoryId)[0];
            console.log(table_categoryData,'options.category')
            // console.log(row.categoryId)
            return table_categoryData.category_name;
            // return table_categoryData
            
        })
        const page = reactive({
            pageNumber: 1,
            pageSize: 8,
        })
        const search_option = reactive([
            { value: 'id',label: 'ID' },
            { value: 'title',label: '标题' }
        ])
        const getList = (()=>{
            // console.log('GetList', '')
            let requestData = formatData();
            //参数不一样会报错
            // let requestData = {
            //     categoryId: '',
            //     startTiem: '',
            //     endTime: '',
            //     title: '',
            //     id: '',
            //     pageNumber: page.pageNumber,
            //     pageSize: page.pageSize   
            // }
            loading_table_data.value = true;
            GetList(requestData).then(response =>{
                // console.log('GetList', '')
                console.log(response.data.data.data)
                //获取列表数据
                let data = response.data.data.data
                table_data.table_dataItem = data
                console.log(table_data.table_dataItem,'11')
                //更新页码
                total.value = response.data.data.total;
                console.log(response.data.data.total, '1111')
                loading_table_data.value = false;

            }).catch((error)=>{
                loading_table_data.value = false;
            })
        })
        const dialogEdit = ((id)=>{
            console.log(id, 'id')
            console.log('dialogEdit', '')
            editId.value = id
            console.log(editId.value, 'editId.value')
            dialog_edit.value = true;
        })




        const deleteItem = ((id)=>{
            deleteInfoId.value = [id];
            confirm({
                content: '是否删除该数据, 是否继续!!!',
                tip: "警告",
                fn: confirmDelete,
                id: "1"
            });
            console.log('deleteitem', '')

            // root.confirm({
            //     content: '是否删除该数据, 是否继续!!!',
            //     tip: "警告",
            //     fn: confirmDelete,
            //     id: "1"
            // });
 
            // console.log('123', '')
        })

        /*
            查看编辑详细 五种路由传参
            明文传参 query 接收：this.$route.query.xxxx
            密文传参 params 接收：this.$route.params.xxxx
            冒号传参 路由例如==path: "/infoDetail/:id/:title" root.$router.push({path: `/InfoDetail/${data.id}/${data.title}`})
            vuex结合html5本地存储
            新窗口打开
         */
        const detail = ((data)=>{   
            console.log(data, 'detail')
            //预留存储
            // root.$store.commit("infoDetail/SET_ID",data.id)
            // root.$store.commit("infoDetail/SET_TITLE",data.title)
            
            root.$store.commit("infoDetail/UPDATE_STATE_VALUE",{
                id:{
                    value: data.id,
                    sessionKey: "infoId",
                    session: true
                },
                title:{
                    value: data.title,
                    sessionKey: "infoTitle",
                    session: true
                }
            })

            //跳转页面
            // root.$router.push({
            //     //ES6
            //     path: `/InfoDetail/${data.id}/${data.title}`
            // })
            root.$router.push({
                name: "InfoDetail",//路由
                // query: {
                //     id: data.id,
                //     title: data.title,
                // }
                params: {
                    id: data.id,
                    title: data.title,
                }
            })

        })

        const deleteAll = (()=>{
            if(!deleteInfoId.value || deleteInfoId.value.length == 0) {
                root.$message({
                    message: "请选择要删除的数据！！",
                    type: "error"
                })
                return false;
            }
            confirm({
                content: '是否批量删除所选的数据, 是否继续!!!',
                tip: "警告",
                fn: confirmDelete,
            });
            console.log('deleteall', '')
            // root.confirm({
            //     content: '是否批量删除所选的数据, 是否继续!!!',
            //     type: "success",
            //     fn: confirmDelete,
            //     id: "2"
            // });
        })
        const confirmDelete = (value)=>{
            console.log('confirmDelete', '')
            // console.log(value)
            options.category = value;
            DeleteInfo({id: deleteInfoId.value}).then(response => {
                console.log(response)
                deleteInfoId.value = '';
                getList()
            }).catch(error =>{

            })

        }
        const handleSelectionChange = (val) => {
            let id = val.map(item => item.id);
            deleteInfoId.value = id
        }
        //获取分类
        // const getCategory = (()=>{
        //     console.log('getCategory', '')
        //     GetCategory({}).then(response =>{
        //         let data=response.data.data.data
        //         console.log(data)
        //         options.category = data
        //         console.log(options.category)
        //         // category.item = data
        //         // console.log(category[0])
        //     }).catch(error =>{

        //     })
        // })
        // console.log('falsetrue')
        // const dialog_info =()=>{
        //     console.log('const dialog_info')
        // }
        //封装方法
        const getInfoCategory=(()=>{
            console.log('信息列表', '')
            // getInfoCategory();
            root.$store.dispatch('common/getInfoCategory').then(response => {
                options.category = response
            })
        })
        //监听watch
        watch(()=> categoryItem.item, (value) =>{
            console.log(value);
            console.log('categoryItem.value', '')
            options.category = value
        });
        //生命周期
        onMounted(()=>{
            console.log('信息列表', '')
            //获取分类
            getInfoCategory();
            // root.$store.dispatch('common/getInfoCategory').then(response => {
            //     options.category = response
            // })
            //获取分类
            getList();

        })
        const handleSizeChange = (val)=>{
            page.pageSize = val;
            console.log(val)
        }
        const handleCurrentChange = (val)=>{
            page.pageNumber = val;
            getList();
            console.log(val)
        }
        // const closeDialog = ()=>{
        //     dialog_info.value=false;
        //     console.log('111111', '')
        // }

        return {
            options,search_option,search_key,category_value,date_value,search_keyWork,
            table_data,table_time,table_search,formatData,
            handleSizeChange,handleCurrentChange,dialog_info,deleteItem,deleteAll,getList,getInfoCategory,
            total,page,loading_table_data,table_categoryId,dialog_edit,dialogEdit,editId,
            handleSelectionChange,detail
            // getCategory
            // closeDialog
        }
    }
}
</script>

<style lang="scss" scoped>
@import "../../styles/config.scss";
@import "../../styles/main.scss";
.lable-wrap{
    &.category{ @include lableDemo(left,40,40); }
    &.date { @include lableDemo(left, 40, 40); }
    &.key-work { @include lableDemo(left, 40, 55); }
}
.text-center{
    text-align: center;
}
/*  class="margin-left-10" ==> main.scss定义了一个方法
*/
</style>
